package com.idb.utils;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import com.idb.annotations.Path;
import lombok.Getter;
import lombok.Setter;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

@Setter
@Getter
public class YmlCache {
    // 默认30分钟过期
    private static final TimedCache<String, Object> CACHE = CacheUtil.newTimedCache(Duration.ofMinutes(30).toMillis());

    public static TimedCache<String, Object> getCache() {
        return CACHE;
    }

    public static <T> T getYml(Class<T> clazz) {
        Path path = clazz.getAnnotation(Path.class);
        return getYml(clazz,path.value());
    }
    public static <T> T getYml(Class<T> clazz,String path) {
        return (T) CACHE.get(clazz.getSimpleName(),() -> {
            createIfNoExist(path,"{}");
            return YmlUtils.load(path,clazz);
        });
    }

    public static <T> void putYml(T object) {
        CACHE.put(object.getClass().getSimpleName(),object);
    }

    public static void createIfNoExist(String path,String context) {
        File file = new File(path);
        if(!FileUtil.exist(file) || FileUtil.isEmpty(file)) {
            // 文件不存在或空内容，创建一个文件
            FileWriter fileWriter = FileWriter.create(file);
            fileWriter.writeFromStream(new ByteArrayInputStream(context.getBytes(StandardCharsets.UTF_8)));
        }
    }

}
